package bit.lotterysystem.controller;

import bit.lotterysystem.common.pojo.CommonResult;
import bit.lotterysystem.common.utils.JacksonUtil;
import bit.lotterysystem.controller.param.DrawPrizeParam;


import bit.lotterysystem.controller.param.ShowWinningRecordsParam;
import bit.lotterysystem.controller.result.WinningRecordResult;
import bit.lotterysystem.service.DrawPrizeService;
import bit.lotterysystem.service.dto.WinningRecordDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@RestController
public class DrawPrizeController {

    private static final Logger logger = LoggerFactory.getLogger(DrawPrizeController.class);

    @Autowired
    private DrawPrizeService drawPrizeService;

    @RequestMapping("/draw-prize")
    private CommonResult<Boolean> drawPrize(@RequestBody @Validated DrawPrizeParam param){

        logger.info("drawPrizeParam:{}", param);
        //service
        drawPrizeService.drawPrize(param);
        return CommonResult.success(true);
    }

    @RequestMapping("/winning-records/show")
    private CommonResult<List<WinningRecordResult>>showWinningRecords(@Validated @RequestBody ShowWinningRecordsParam param){
        logger.info("showWinningRecordsParam:{}", JacksonUtil.writeValueAsString(param));
        List<WinningRecordDTO>winningRecordDTOList=drawPrizeService.getRecords(param);
        return CommonResult.success(convertToWinningRecordDTOList(winningRecordDTOList));
    }

    private List<WinningRecordResult> convertToWinningRecordDTOList(
            List<WinningRecordDTO> winningRecordDTOList) {
        if(CollectionUtils.isEmpty(winningRecordDTOList)){
            return Arrays.asList();
        }
        return winningRecordDTOList.stream()
                .map(winningRecordDTO -> {
                    WinningRecordResult winningRecordResult = new WinningRecordResult();
                    winningRecordResult.setWinnerId(winningRecordDTO.getWinnerId());
                    winningRecordResult.setWinnerName(winningRecordDTO.getWinnerName());
                    winningRecordResult.setPrizeName(winningRecordDTO.getPrizeName());
                    winningRecordResult.setPrizeTier(winningRecordDTO.getPrizeTier().getMessage());
                    winningRecordResult.setWinningTime(winningRecordDTO.getWinningTime());
                    return winningRecordResult;
                }).collect(Collectors.toList());
    }
}
